// 帖子图片上传适配器（为 CKEditor5 准备）
import { FileLoader, UploadAdapter,UploadResponse } from '@ckeditor/ckeditor5-upload'
import {FmsFileInfo} from 'src/lib/defs/fms'
import axios, {AxiosProgressEvent, CancelTokenSource} from 'axios'
import _ from 'lodash'

const fileBaseUrl = $f.appCfg.apiBaseUrl + '/comm/fms/file/'

//帖子图片文件上传适配器
export default class PostImgUploadAdapter implements UploadAdapter {
  loader:FileLoader
  cancelTokenSource: CancelTokenSource
  constructor(loader:FileLoader) {
    this.loader = loader
    this.cancelTokenSource = axios.CancelToken.source()
  }
  upload():Promise<UploadResponse> {
    return new Promise<UploadResponse>((resolve, reject) => {
      this.loader.file.then(file => {
        if(file==null){
          reject('未选中图片文件')
        }
        else{
          const formData = new window.FormData()
          formData.append('file', file)
          $f.axios
            .post<FmsFileInfo>('/misc-test/upload-post-image/1', formData, {
              //进度条处理
              onUploadProgress: (progressEvent:AxiosProgressEvent) => {
                if(_.isNumber(progressEvent.total) && _.isNumber(progressEvent.loaded)){
                  //进度条显示不出来，不确定是不是需要额外的插件或者还需要实现些什么接口
                  this.loader.uploadTotal = progressEvent.total
                  this.loader.uploaded = progressEvent.loaded
                }
              },
              cancelToken: this.cancelTokenSource.token,
            })
            .then((resp) => {
              resolve({default:fileBaseUrl+resp.data.fileUuid})
            })
            .catch((err) => {
              reject($f.getAxiosErrMsg(err))
            })
        }
      })
    })
  }
  abort():void {
    if ( this.cancelTokenSource ) {
      this.cancelTokenSource.cancel('用户取消图片上传')
    }
  }
}

